package com.panda.business.service;

import Jubo.JuLiao.IM.Wx.Proto.PostSNSNewsTask.PostSNSNewsTaskMessage;
import Jubo.JuLiao.IM.Wx.Proto.PostSNSNewsTask.PostSNSNewsTaskMessage.AttachmentMessage;
import Jubo.JuLiao.IM.Wx.Proto.PostSNSNewsTask.PostSNSNewsTaskMessage.VisibleMessage;
import Jubo.JuLiao.IM.Wx.Proto.PostSNSNewsTask.PostSNSNewsTaskMessage.VisibleMessage.EnumVisibleType;
import Jubo.JuLiao.IM.Wx.Proto.WeChatGroupSendTask.WeChatGroupSendTaskMessage;
import com.google.protobuf.util.JsonFormat;
import com.panda.business.mapper.TaskTimeMapper;
import com.panda.business.mapper.TimeTaskDetailsMapper;
import com.panda.business.domain.TaskTimeInfo;
import com.panda.business.domain.TimeTaskDetails;
import com.panda.framework.domain.base.DBPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Transactional // 支持事务
public class TaskTimeService {
	  
	@Autowired
	private TaskTimeMapper taskTimeMapper;
	
	@Autowired
	private TimeTaskDetailsMapper timeTaskDetailsMapper;
 
 
	public List<TaskTimeInfo> queryTaskTimeInfoByAccountId(TaskTimeInfo info){
		DBPage page = new DBPage(info.getPageSize(), (info.getPageNo() - 1) * info.getPageSize());
		return taskTimeMapper.queryTaskTimeInfoByAccountId(page,info.getAccountid(), info.getTasktype(), info.getState());
	}
	

	public TaskTimeInfo findTaskTimeInfoByid(Integer id) {
		return taskTimeMapper.findTaskTimeInfoByid(id);
	}
 

	public void delete(Integer id) {
		try {
			//先删除子任务
			timeTaskDetailsMapper.deleteByTid(id);
			//再删除主任务
			TaskTimeInfo user = new TaskTimeInfo();
			user.setId(id);
			taskTimeMapper.delete(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void updateState(TaskTimeInfo info) {
		taskTimeMapper.updateState(info);
	}
	
	public List<TaskTimeInfo> findTaskTimeByTime(String execute_time){
		return taskTimeMapper.findTaskTimeByTime(execute_time);
	}
	
	public List<TimeTaskDetails> findTimeTaskDetailsByTid(Integer tid){
		return timeTaskDetailsMapper.findTimeTaskDetailsByTid(tid);
	}
	 
	
	private static void saveCircleSendTimeTaskDetail(TaskTimeInfo info, List<String> friendWechatList, String wechatId , TimeTaskDetailsMapper timeTaskDetailsMapper){
		if(null != info.getId()){
			List<String> newfriendWechatList =  null;
			if( null != friendWechatList && friendWechatList.size()>0){
				//friendWechatList去除重复
				newfriendWechatList = removeRepeat(friendWechatList);
			}
	    	
	    	TimeTaskDetails detail = new TimeTaskDetails();
	    	detail.setTid(info.getId());
	    	detail.setExecute_time(info.getExecute_time());
	    	timeTaskDetailsMapper.insert(detail);
	    	
	    	if(null != detail.getId()){
	    		//设置附件
	    		AttachmentMessage.Builder attachment = AttachmentMessage.newBuilder();
	    		attachment.setTypeValue(info.getRestype());
	    		attachment.addAllContent(stringToList(info.getAttachtcontent()));
	    		//设置可见范围
	    		VisibleMessage.Builder  visible  = VisibleMessage.newBuilder();
	    		visible.setTypeValue(EnumVisibleType.WhoInvisible_VALUE);//不给谁看
	    		visible.setFriends(ListToString(newfriendWechatList));
	    		 
	    		//按微信号生成需要发的消息内容
	    		PostSNSNewsTaskMessage.Builder buider = PostSNSNewsTaskMessage.newBuilder();
				buider.setContent(info.getContent());
				buider.setAttachment(attachment);
				buider.setTaskId(detail.getId());
				buider.setWeChatId(wechatId);
				buider.setComment(info.getComment());
				buider.setVisible(visible);
				PostSNSNewsTaskMessage msg = buider.build();
				String json = null;
				if (null != msg) {
					try {
						json = JsonFormat.printer().print(msg);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if(!StringUtils.isEmpty(json)){
					TimeTaskDetails tds =  new TimeTaskDetails();
					tds.setId(detail.getId());
					tds.setJson_content(json);
					timeTaskDetailsMapper.updateJsonContent(tds);
				}
	    	}
	    }
		
	}
	
	private static void saveGroupSendTimeTaskDetail(TaskTimeInfo info, List<String> friendWechatList, String wechatId , TimeTaskDetailsMapper timeTaskDetailsMapper){
		if(null != info.getId() ){
			List<String> newfriendWechatList = null;
			if(null != friendWechatList && friendWechatList.size()>0){
				newfriendWechatList = removeRepeat(friendWechatList);//friendWechatList去除重复
			}
	    	 
	    	TimeTaskDetails detail = new TimeTaskDetails();
	    	detail.setTid(info.getId());
	    	detail.setExecute_time(info.getExecute_time());
	    	timeTaskDetailsMapper.insert(detail);
	    	
	    	if(null != detail.getId()){
	    		//按微信号生成需要群发的消息内容
				WeChatGroupSendTaskMessage.Builder buider = WeChatGroupSendTaskMessage.newBuilder();
				buider.setContent(info.getContent());
				buider.setContentTypeValue(info.getRestype());
				buider.setTaskId(detail.getId());
				buider.setWeChatId(wechatId);
				buider.addAllFriendIds(newfriendWechatList);
				WeChatGroupSendTaskMessage msg = buider.build();
				String json = null;
				if (null != msg) {
					try {
						json = JsonFormat.printer().print(msg);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if(!StringUtils.isEmpty(json)){
					TimeTaskDetails tds =  new TimeTaskDetails();
					tds.setId(detail.getId());
					tds.setJson_content(json);
					timeTaskDetailsMapper.updateJsonContent(tds);
				}
	    	}
	    }
		
	}
	
  
    private static List<String> stringToList(String str){
    	List<String> list = new ArrayList<>();
    	if(!StringUtils.isEmpty(str)){
    		String [] s = str.split(",");
    		if(null != s && s.length>0){
    			for(int i=0;i<s.length;i++){
    				list.add(s[i]);
    			}
    		}else{
    			list.add(str);
    		}
    	}
    	return list;
    }
    
    private static String ListToString(List<String> list){
    	String s = "";
    	if(null != list && list.size()>0){
    		for(int i=0;i<list.size();i++){
    			s = s + list.get(i) +",";
    		}
    	}
    	if(!StringUtils.isEmpty(s) && s.endsWith(",")){
    		s = s.substring(0, s.length()-1);
    	}
    	return s;
    	
    }
    
    private static List<String> removeRepeat(List<String> list){
    	Set<String> set = new  HashSet<>(); 
        List<String> newList = new  ArrayList<String>(); 
        for (String cd:list) {
           if(set.add(cd)){
               newList.add(cd);
           }
       }
    	return newList;
    }
    
    /**
     * pc端添加定时任务
     * @param info
     * @return
     */
    public String savePcTask(TaskTimeInfo info) {
		String res = "success";
		try {
			List<String> wechatList = info.getWechatList();
			 
			//主任务存储数据库
			info.setState(1);//1开启中 0已完成
		    taskTimeMapper.insert(info);
		      
		    //子任务分别处理  存储子任务详情 
			if(info.getTasktype()==1){//添加群发任务
		       saveGroupSendTimeTaskDetail(info, wechatList, info.getWechatId(), timeTaskDetailsMapper);
			}else if(info.getTasktype()==2){//发朋友圈
			   saveCircleSendTimeTaskDetail(info, stringToList(info.getWhoinvisible()), info.getWechatId(), timeTaskDetailsMapper);
			}
			     
		} catch (Exception e) {
			res = "fail";
			e.printStackTrace();
		}

		return res;
	}
    

}
